package com.njit.WeStudy.control;

import com.njit.WeStudy.config.NeedLogin;
import com.njit.WeStudy.dao.*;
import com.njit.WeStudy.dataobject.*;
import com.njit.WeStudy.dataobject.Class;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

import static com.njit.WeStudy.util.MD5.getMD5String;

/**
 * @author yuruiqiao
 * @date 2020/1/28
 * @description 登录控制类
 */
@Controller
public class loginController {
    @Resource
    private UserMapper userMapper;

    @Resource
    private InvitationMapper invitationMapper;

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private StarMapper starMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private StoreyMapper storeyMapper;

    @Resource
    private ClassMapper classMapper;

    @Resource
    private JoinClassMapper joinClassMapper;

    @Resource
    private InviteCodeMapper inviteCodeMapper;
    /**
     * 登录方法
     * 2020-01-18
     * */
    @RequestMapping(path = "/doLogin")
    //此username并不是user表里面的user_name，而是phone或者email
    public String login(@RequestParam(value = "username")String username, ModelMap modelMap,
                              @RequestParam(value = "password")String password, HttpSession session){
        if(!username.equals("") && !password.equals("")){
            //MD5加密
            String passwordByMD5 = getMD5String(password);
            List<User> userByPhone = userMapper.selectBy("phone",username);//手机号登录
            List<User> userByEmail = userMapper.selectBy("email",username);//邮箱登录
            if(userByPhone.size()>0){
                if(userByPhone.get(0).getPassword().equals(passwordByMD5)){
                    session.setAttribute("user",userByPhone.get(0));
                    return viewIndex(modelMap,session);
                }
            }else if(userByEmail.size()>0){
                if(userByEmail.get(0).getPassword().equals(passwordByMD5)){
                    session.setAttribute("user",userByEmail.get(0));
                    return viewIndex(modelMap,session);
                }
            }
        }
        modelMap.addAttribute("username",username);
        modelMap.addAttribute("errorMsg","*用户名或密码错误");
        return "login";
    }
    /**
     * 假如直接访问localhost:8080处理
     * 2020-01-18
     * */
    @RequestMapping(path = "/")
    public String viewIndex(ModelMap modelMap,HttpSession session){
        try{
            int userId = ((User)session.getAttribute("user")).getUserId();
            //是否点赞
            List<Like> myLikes =likeMapper.likeQueryByUserId(userId);
            List<Integer> likeInvitationIds = new ArrayList<>();
            for (Like myLike : myLikes) {
                likeInvitationIds.add(myLike.getInvitationId());
            }
            modelMap.addAttribute("likeInvitationIds",likeInvitationIds);
            //是否收藏帖子
            List<Star> myStars =starMapper.starQueryByUserId(userId,"invitation");
            List<Integer> starInvitationIds = new ArrayList<>();
            for (Star myStar : myStars) {
                starInvitationIds.add(myStar.getTargetId());
            }
            modelMap.addAttribute("starInvitationIds",starInvitationIds);
            //是否关注用户
            List<Star> myUserStars =starMapper.starQueryByUserId(userId,"user");
            List<Integer> starUserIds = new ArrayList<>();
            for (Star myUserStar : myUserStars) {
                starUserIds.add(myUserStar.getTargetId());
            }
            modelMap.addAttribute("starUserIds",starUserIds);

            //是否跟帖
            List<Storey> myStoreys = storeyMapper.storeyQueryByUserId(userId);
            List<Integer> storeyInvitationIds = new ArrayList<>();
            for (Storey myStorey : myStoreys) {
                storeyInvitationIds.add(myStorey.getInvitationId());
            }
            modelMap.addAttribute("storeyInvitationIds",storeyInvitationIds);
            //是否回复
            List<Comment> comments = commentMapper.commentQueryByUserId(userId);
            List<Integer> commentInvitationIds = new ArrayList<>();
            for (Comment comment : comments) {
                commentInvitationIds.add(comment.getInvitationId());
            }
            modelMap.addAttribute("commentInvitationIds",commentInvitationIds);
        }catch (NullPointerException ne){
            System.out.print("");
        }
        List<InvitationView> invitationViews = invitationMapper.selectAllView();
        modelMap.addAttribute("invitations",invitationViews);
        return "index";
    }

    /**
     * 访问localhost:8080/login处理
     * 2020-01-18
     * */
    @RequestMapping(path = "/login")
    public String viewLogin(){
        return "login";
    }

    /**
     * 注销登录
     * 2020-01-18
     * */
    @RequestMapping(path = "/logout")
    public String logout(HttpSession session,ModelMap modelMap){
        List<InvitationView> InvitationViews = invitationMapper.selectAllView();
        modelMap.addAttribute("invitations",InvitationViews);
        session.removeAttribute("user");
        return "index";
    }
    /**
     * @author yuruiqiao
     * @date 2020/2/5
     * @description 跳转到classes页面
     */
    @RequestMapping(path = "/classes")
    public String classes(ModelMap modelMap,HttpSession session){
        try{
            int userId = ((User)session.getAttribute("user")).getUserId();
            List<JoinClass> joinClasses = joinClassMapper.joinClassQueryByUserId(userId);
            List<Integer> myClassIds = new ArrayList<>();
            for (JoinClass joinClass : joinClasses) {
                myClassIds.add(joinClass.getClassId());
            }
            modelMap.addAttribute("myClassIds",myClassIds);

        }catch (NullPointerException ne){
            System.out.println();
        }catch (Exception e){
            e.printStackTrace();
        }
        List<Invitation> invitations = invitationMapper.selectAll();
        modelMap.addAttribute("invitations",invitations);
        List<ClassView>classes = classMapper.selectAllView();
        modelMap.addAttribute("classes",classes);
        return "classes";
    }
    /**
     * @author yuruiqiao
     * @date 2020/2/9
     * @description 跳转到class详情页面
     */
    @RequestMapping(path = "/class-details")
    @NeedLogin
    public String classDetails(HttpSession session,ModelMap modelMap,@RequestParam("classId") int classId){
        try{
            int userId = ((User)session.getAttribute("user")).getUserId();
            List<JoinClass> joinClasses = joinClassMapper.joinClassQueryByUserId(userId);
            for (JoinClass joinClass : joinClasses) {
                if(joinClass.getClassId()==classId){
                    Class newClass = classMapper.selectViewByPrimaryKey(classId);
                    modelMap.addAttribute("class",newClass);
                    List<InviteCode> codes = inviteCodeMapper.inviteCodeQueryByClassId(classId);
                    modelMap.addAttribute("codes",codes);
                    List<Student> students = joinClassMapper.joinClassQueryByClassId(classId);
                    modelMap.addAttribute("students",students);
                    return "class-details";//如果查询到则返回详情页
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //否则返回列表页
        List<Invitation> invitations = invitationMapper.selectAll();
        modelMap.addAttribute("invitations",invitations);
        List<ClassView>classes = classMapper.selectAllView();
        modelMap.addAttribute("classes",classes);
        return "classes";
    }
}
